// ActionScript file
import COMPONENTS.MenuControl;
import COMPONENTS.twClientBill;
import COMPONENTS.twCounterCopyBill;
import COMPONENTS.twDiscountPassword;
import COMPONENTS.twItemsPrice;
import COMPONENTS.twKitchenQT;
import COMPONENTS.twResetReason;

import ENUMS.ApplicationVariables;
import ENUMS.SlotStatus;

import EVENTS.DiscountStatusEvent;
import EVENTS.ResetCommitted;
import EVENTS.SlotStatusChangedEvent;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.ui.Keyboard;
import flash.utils.setTimeout;

import mx.controls.Alert;
import mx.core.UITextField;
import mx.events.ListEvent;
import mx.managers.PopUpManager;

import org.flexlancer.Logger.Logger;
import org.flexlancer.databases.AdditionalDishes;
import org.flexlancer.databases.AppVars;
import org.flexlancer.databases.Bill;
import org.flexlancer.databases.DishCategories;
import org.flexlancer.databases.ResetBill;

public static const REPORT_ME:String = "ReportMe";

[Bindable]
private var arrBill:Array = new Array();
[Bindable]
private var xmllistCategories:XMLList = new XMLList();
[Bindable]
private var xmllistAddtionalItems:XMLList = new XMLList();
[Bindable]
private var xmllistItems:XMLList = new XMLList();
[Bindable]
public var defaultServiceCharges:Boolean = false;
[Bindable]
public var delivery_charges:String = "";

private var menu_file_name:String = "";

public function set MenuFile(val:String):void{
	this.menu_file_name = val;
}

private function UpdateTime():void{
	try{
		var dtNow:Date = new Date();
		this.lblDateTime.text = dtNow.toDateString() + " " + dtNow.toLocaleTimeString();
		setTimeout(this.UpdateTime,1000);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function OnMainKeyUp(evt:KeyboardEvent):void{
	try{
		var singleO:Object;
		switch(evt.keyCode){
			case Keyboard.CONTROL:
				if ( evt.target is UITextField ){
					this.tlCategories.setFocus();
					this.tlCategories.selectedIndex = 0;
				}else{
					this.txtCode.setFocus();
				}
				evt.stopImmediatePropagation();
				break;
			case Keyboard.END:
				this.txtAmountPaid.setFocus();
				break;
			case Keyboard.F2:
				this.dgCurrentPurchase.setFocus();
				break;
			case Keyboard.F5:
				this.PrintKitchen_OnClick();
				break;
			case Keyboard.F6:
				this.OnPayBill();
				break;
				
			case Keyboard.F3:
				for each ( singleO in this.dgCurrentPurchase.selectedItems ){
					singleO.ps = "P";
				}
				this.dgCurrentPurchase.dataProvider = this.arrBill;
				break;
			case Keyboard.F4:
				for each ( singleO in this.dgCurrentPurchase.selectedItems ){
					singleO.ps = "S";
				}
				this.dgCurrentPurchase.dataProvider = this.arrBill;
				//this.dgCurrentPurchase.selectedItem.ps = "S";
				//this.dgCurrentPurchase.dataProvider = this.arrBill;
				break;
			case Keyboard.DELETE:
				this.Del_OnClick();
				evt.stopImmediatePropagation();
				//prev_index = 0; 
				break;
			case Keyboard.P:
				this.OnPrintBill();
				break;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function get IsEmptyBill():Boolean{
	return this.arrBill.length == 0 ? true : false;
}

private function setStartFocus():void{
	if ( this.currentState == null || this.currentState == "" )
		this.txtCode.setFocus();
}

private function OnCC():void{
	try{
		var ldr:URLLoader = new URLLoader(new URLRequest(this.menu_file_name));
		ldr.addEventListener(Event.COMPLETE,OnMenuLoad);
		this.dgCurrentPurchase.dataProvider = this.arrBill;
		this.callLater(this.ComputeTotal);
		this.UpdateTime();
		setTimeout(this.setStartFocus,1000);
		this.tlCategories.addEventListener(MouseEvent.MOUSE_WHEEL,OnItemsMouseWheel,true);
		this.tlItems.addEventListener(MouseEvent.MOUSE_WHEEL,OnItemsMouseWheel,true);
		setTimeout(this.ResetScroll,100);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function get QTData():Object{
	try{
		var qtdata:Object = new Object();
		qtdata.arrBill = this.arrBill;
		return qtdata;
	}catch(err:Error){
		Logger.LogE(err);
	}
	return new Object();
}

public function set QTData(val:Object):void{
	try{
		if ( val == null || val.arrBill == undefined || val.arrBill == null ){
			this.arrBill = new Array();
		}else{
			this.arrBill = val.arrBill;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function ShowItemsandPrice():void {
	try {
		var twItemsandPrice:twItemsPrice = PopUpManager.createPopUp(this,twItemsPrice,true) as twItemsPrice;
		PopUpManager.centerPopUp(twItemsandPrice);
	}catch(err:Error) {
		Logger.LogE(err);
	}
}

private var extracheeseprice:Number = 0;
private var extrasouceprice:Number = 0;
private var masalariceprice:Number = 0;

private function LoadMenuFromDB():void{
	try{
		var menudata:Array = DishCategories.Menu();
		var prop:String = "";
		
		switch(this.menu_file_name){
			case ApplicationVariables.DINE_IN_MENU:
				prop = "dinein";	
			break;
			case ApplicationVariables.TAKEY_AWAY_MENU:
				prop = "takeaway";	
			break;
			case ApplicationVariables.DELIVERY_MENU:
				prop = "delivery";	
			break;
			default:
			break;
		}
		
		var xmldata:XML = new XML(<Menu />);
		
		for each ( var singleGroup:Object in menudata ){
			var insertGroup:XML = new XML(<Group />);
			insertGroup.@name = String(singleGroup.catname).toUpperCase();
			insertGroup.@price = "";
			
			for each ( var singleDish:Object in singleGroup.children ){
				if ( singleDish[prop] >= 0 ){
					var insertDish:XML = new XML(<Dish />);
					insertDish.@name = String(singleDish.itemname).toUpperCase();
					insertDish.@price = singleDish[prop];
					insertDish.@code = singleDish.itemcode;
					
					insertGroup.appendChild(insertDish);
				}
			}
			
			if ( insertGroup.children().length() > 0 ){			
				xmldata.appendChild(insertGroup);
			}
		}
		
		this.xmllistCategories = xmldata.children();
		
		xmldata = new XML(<AdditionalItem />);
		xmldata.appendChild(new XML(<Extra name="" price="0" />));
		for each ( var saItem:Object in AdditionalDishes.List() ){
			if ( saItem[prop] >= 0 ){
				var insertAItem:XML = new XML(<Extra />);
				insertAItem.@name = saItem.itemname;
				insertAItem.@price = saItem[prop];
				xmldata.appendChild(insertAItem);
			}
		}
		
		this.xmllistAddtionalItems = xmldata.children();
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnMenuLoad(evt:Event):void{
	try{
		this.LoadMenuFromDB();
		/*
		var xml:XML = new XML(evt.target.data);
		this.xmllistCategories = xml.children();
		this.extracheeseprice = Number(xml.@extrac);
		this.extrasouceprice = Number(xml.@extras);
		this.masalariceprice = Number(xml.@masalar);
		*/
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnCategoryClicked(evt:ListEvent = null):void{
	try{
		var xml:XML = this.tlCategories.selectedItem as XML;
		this.xmllistItems = xml.children();
		
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnItemClicked(evt:ListEvent = null):void{
	try{
		var xml:XML = this.tlItems.selectedItem as XML;
		xml.@cat = this.tlCategories.selectedItem.@name;
		this.AddItemIntoBill(xml,1,this.cmbExtra.selectedItem);		
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnCodeEnter():void{
	try{
		if ( this.txtCode.text != "" ){
			var code:Number = Number(this.txtCode.text);
			var qty:Number = this.txtQty.text == "" ? 1 : Number(this.txtQty.text);
			for each ( var singleItem:XML in this.xmllistCategories..Dish ){
				if ( singleItem.@code == code ){
					this.AddItemIntoBill(singleItem,qty,this.cmbExtra.selectedItem);
					return;
				}
			}
			Alert.show("Invalid Code Entered");
			this.InputReset();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnCodeKeyUp(evt:KeyboardEvent):void{
	try{
		if ( evt.keyCode == Keyboard.RIGHT ) {
			this.txtQty.setFocus();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnQtyKeyUp(evt:KeyboardEvent):void{
	try{
		if ( evt.keyCode == Keyboard.RIGHT ) {
			this.cmbExtra.setFocus();
		}
		if ( evt.keyCode == Keyboard.LEFT ) {
			this.txtCode.setFocus();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnExtraKeyUp(evt:KeyboardEvent):void{
	try{
		switch(evt.keyCode){
			case Keyboard.LEFT :
				this.txtQty.setFocus();
				break;
			case Keyboard.ENTER:
				this.OnCodeEnter();
				break;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function UpdateSrno():void{
	try{
		var srno:Number = 1;
		for each ( var singleItem:Object in this.arrBill ) {
			singleItem.srno = srno;
			srno++;
		}
		
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnCategory_KeyUp(evt:KeyboardEvent):void{
	try{
		if ( evt.keyCode == Keyboard.PAGE_DOWN || evt.keyCode == Keyboard.ENTER ) {
			this.tlItems.setFocus();
			this.tlItems.selectedIndex = 0;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnItem_KeyUp(evt:KeyboardEvent):void{
	try{
		if ( evt.keyCode == Keyboard.PAGE_UP ) {
			this.tlCategories.setFocus();
			this.tlCategories.selectedIndex = 0;
		}
		
		if ( evt.keyCode == Keyboard.ENTER ) {
			this.OnItemClicked();
		}
		
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnDG_KeyUp(evt:KeyboardEvent):void{
	try{
		/*if ( this.dgCurrentPurchase.selectedItems.length == 0 ) return;
		
		var prev_index:int = this.dgCurrentPurchase.selectedIndex;
		var singleO:Object;
		
		switch ( evt.keyCode ){
			case Keyboard.F3:
				for each ( singleO in this.dgCurrentPurchase.selectedItems ){
					singleO.ps = "P";
				}
				this.dgCurrentPurchase.dataProvider = this.arrBill;
				break;
			case Keyboard.F4:
				for each ( singleO in this.dgCurrentPurchase.selectedItems ){
					singleO.ps = "S";
				}
				this.dgCurrentPurchase.dataProvider = this.arrBill;
				//this.dgCurrentPurchase.selectedItem.ps = "S";
				//this.dgCurrentPurchase.dataProvider = this.arrBill;
				break;
			case Keyboard.DELETE:
				this.Del_OnClick();
				evt.stopImmediatePropagation();
				prev_index = 0; 
				break;
		}		
		
		this.dgCurrentPurchase.selectedIndex = prev_index;
		*/
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function AddItemIntoBill(val:XML,qty:Number = 1,extra:Object=null):void{
	try{
		var already:Boolean = false;
		var extrap:Number = 0;
		var exttitle:String = ( extra ? extra.@name : "");
		var extprice:Number = ( extra ? Number(extra.@price) : 0 );
		for each ( var singleItem:Object in this.arrBill ) {
			if ( singleItem.status != ApplicationVariables.PRINT_KITCHEN && singleItem.code == val.@code && singleItem.extra==exttitle){
				
				extrap = Number(extprice);
				/*
				switch ( extra ){
					case "CH": extrap = this.extracheeseprice; break;
					case "SO": extrap = this.extrasouceprice; break;
					case "MR": extrap = this.masalariceprice; break;
				}
				*/
				singleItem.qty+=qty;
				singleItem.total = singleItem.qty * (singleItem.price + extrap);
				already = true;
				break;
			}
		}

		if ( !already ){
			var insertObj:Object = new Object();
			insertObj.srno = this.arrBill.length + 1;
			insertObj.code = String(val.@code);
			insertObj.title = String(val.@name);
			insertObj.qty = qty;
			insertObj.ps = "S";
			insertObj.extra = exttitle;
			
			extrap = Number(extprice);
			/*
			switch ( extra ){
				case "CH": extrap = this.extracheeseprice; break;
				case "SO": extrap = this.extrasouceprice; break;
				case "MR": extrap = this.masalariceprice; break;
			}*/
			
			insertObj.price = Number(val.@price);
			insertObj.total = (insertObj.price + extrap) * qty;
			
			insertObj.cat = String(val.parent().@name);
			
			this.arrBill.push(insertObj);
		}
		
		this.UpdateSrno();
		
		this.dgCurrentPurchase.dataProvider = this.arrBill;
		
		this.ComputeTotal();
		this.dispatchEvent(new Event(MenuControl.REPORT_ME));
		this.InputReset();
		setTimeout(this.ResetScroll,100);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function ResetScroll():void{
		this.dgCurrentPurchase.verticalScrollPosition = this.dgCurrentPurchase.maxVerticalScrollPosition;
}
private var discount_rate:Number = 0;
private var discount_note:String = "";
private var service_charges:Number = 0;
private var discount_amount:Number = 0;
private var tax_amount:Number = 0;
private var init_total:Number = 0;

private function ComputeTotal():void{
	try{
		var gtotal:Number = 0;
		var tax:Number = 0;
		var service_charges:Number = 0;
		var delivery_charges:Number = 0;
		var discount:Number = 0;
		
		for each ( var singleItem:Object in this.arrBill ) {
			gtotal += singleItem.total;
		}
		
		this.init_total = gtotal;
		
		if ( this.chkApplyTAX.selected ) {
			tax = Math.floor(0.17*gtotal);
			this.tax_amount = tax;
			this.chkApplyTAX.label = "Apply TAX = " + gtotal.toString() + "+" + tax.toString();
		}else{
			this.chkApplyTAX.label = "Apply TAX";
			this.tax_amount = 0;
		}
		
		if ( this.currentState == null || this.currentState == "" ){
			if ( this.chkServiceCharges.selected ) {
				service_charges = Math.floor(gtotal * 0.05);
				this.chkServiceCharges.label = "Service Charges = " + service_charges.toString();
				this.service_charges = service_charges;
			}else{
				this.chkServiceCharges.label = "Service Charges";
				this.service_charges = 0;
			}
		}else{
			service_charges = Number(this.txtDeliveryCharges.text==""?"0":this.txtDeliveryCharges.text)
			this.service_charges = service_charges;
		}
		
		if ( this.chkDiscount.selected ) {
			discount = Math.floor(gtotal * this.discount_rate / 100 );
			this.discount_amount = discount;
			this.chkDiscount.label = "M.A.K = " + discount.toString() + " ("+this.discount_rate.toString()+"%)"; 
		}else{
			this.chkDiscount.label = "M.A.K";
			this.discount_amount = 0;
		}
		this.txtTotal.text = (gtotal + tax + service_charges - discount).toString();
		this.OnAmountPaidChanged();
	}catch(err:Error){
		Logger.LogE(err);
	}
}
public var lastQTNumber:Number = 0;
public var isResetQT:Boolean = false;

private function AddNewKitchenPrint(parmItems:Array):void{
	try{
		var prt:Object = this.parent;
		var custInfo:Object = prt.CustomerInfo();
		var goForKit:twKitchenQT = PopUpManager.createPopUp(this,twKitchenQT,true) as twKitchenQT;
		var cname:String = "";
		var cnumber:String = "";
		var caddress:String = "";
		var carea:String = "";
		var cnote:String = "";
		var new_qt:Number = AppVars.GetNextKitchenQT();
		var qtInfo:String = "K.QT: "+new_qt;
		
		if ( this.isResetQT ){
			qtInfo = "Order Change: " + this.lastQTNumber.toString() + "\n" + qtInfo;
		}else if ( this.lastQTNumber > 0 ){
			qtInfo = "Running QT: " + this.lastQTNumber.toString() + "\n" + qtInfo;
		}
		
		this.isResetQT = false;
		this.lastQTNumber = new_qt;
		
		if ( custInfo != null ){
			cname = custInfo.name;
			cnumber = custInfo.telephone;
			caddress = custInfo.address;
			carea = custInfo.area;
			cnote = custInfo.note;
		}
		goForKit.SetValues(qtInfo,this.billCat,this.slotID.toString(),this.server,parmItems,cname,cnumber,caddress,carea,cnote);
		PopUpManager.centerPopUp(goForKit);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function PrintKitchen_OnClick():void{
	try{
		var arrItems:Array = new Array();
		for each ( var singleItem:Object in this.arrBill ){
			if ( singleItem.status != ApplicationVariables.PRINT_KITCHEN ){
				arrItems.push({name:singleItem.title , extra:singleItem.extra, qty:singleItem.qty, ps:singleItem.ps});
			}
			singleItem.status = ApplicationVariables.PRINT_KITCHEN;
		}
		this.dgCurrentPurchase.dataProvider = this.arrBill;
		this.dispatchEvent(new Event(MenuControl.REPORT_ME));
		this.AddNewKitchenPrint(arrItems);
		Object(this.parent).UpdateTitle();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function Del_OnClick():void{
	try{
		if ( this.dgCurrentPurchase.selectedItems.length != 0 ){
			
			var new_items:Array = new Array;
			
			for each ( var singleO:Object in this.arrBill ) {
				if ( singleO.status == ApplicationVariables.PRINT_KITCHEN ){
					Alert.show("Unable to delete item, It is already in Kitchen","Delete Error");
					return;
				} else if ( this.dgCurrentPurchase.selectedItems.indexOf(singleO) < 0 ){
					new_items.push(singleO);
				}
			}
			this.arrBill = new_items;
			this.UpdateSrno();
			this.dgCurrentPurchase.dataProvider = this.arrBill;
			this.ComputeTotal();
			this.dispatchEvent(new Event(MenuControl.REPORT_ME));
		}
		this.InputReset();
		
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function Reset_OnClick():void{
	try{
		//this.arrBill = new Array();
		for ( var i:Number = 0 ; i < this.arrBill.length ; i ++ ){
			var obj:Object = this.arrBill[i];
			if ( obj.status != ApplicationVariables.PRINT_KITCHEN ){
				this.arrBill.splice(i,1);
				i--;
			}
		}
		this.UpdateSrno();
		this.dgCurrentPurchase.dataProvider = this.arrBill;
		this.ComputeTotal();
		this.InputReset();
		this.dispatchEvent(new Event(MenuControl.REPORT_ME));
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function InputReset():void{
	try{
		this.txtCode.text = this.txtQty.text = "";
		this.cmbExtra.selectedIndex = 0; 
		this.txtCode.setFocus();		
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnTaxApplyChange():void{
	try{
		this.ComputeTotal();
		this.OnAmountPaidChanged();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnServiceChargesChange():void{
	try{
		this.ComputeTotal();
		this.OnAmountPaidChanged();
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnDiscountChange():void{
	try{
		if ( this.chkDiscount.selected ){
			var twGetDiscount:twDiscountPassword = PopUpManager.createPopUp(this,twDiscountPassword,true) as twDiscountPassword;
			twGetDiscount.addEventListener(DiscountStatusEvent.DISCOUNT_STATUS_SET,OnDiscountStatusSet);
			PopUpManager.centerPopUp(twGetDiscount);
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnDiscountStatusSet(evt:DiscountStatusEvent):void{
	try{
		if ( evt.DisountVerified ){
			this.discount_rate = evt.DiscountRate;
			this.discount_note = evt.DiscountNote;
			this.ComputeTotal();
		}else{
			this.chkDiscount.selected = false;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public var server:String = "";
public var billCat:String = "";
public var slotID:Number = 0;
private var sales_note:String = "";

private function OnPayBill():void{
	try{
		if ( this.arrBill.length == 0 ) return;
		if ( !this.btnPayBill.enabled ) return;
		
		var prt:Object = this.parent;
		var custInfo:Object = prt.CustomerInfo();
		
		var haveapptax:Number = this.chkApplyTAX.selected ? 1 : 0;
		var haveservcharg:Number = this.chkServiceCharges.selected ? 1 : 0;
		var havediscount:Number = this.chkDiscount.selected? 1 : 0;

		if ( this.currentState == "DeliveryState" ){
			if ( this.server.toUpperCase() == "NO RIDER" ){
				Alert.show("Please select the rider.");
				return;
			}
			if ( this.service_charges == 0 ) haveservcharg = 0;
			else haveservcharg = 1;
		}
		var customername:String = "";
		var customernumber:String = "";
		var customeraddress:String = "";
		var customerarea:String = "";
		var salesnote:String = "";
		
		if ( custInfo != null ){
			if ( ! prt.SaveCustomer() ){
				return;
			}

			customername = custInfo.name;
			customernumber = custInfo.telephone;
			customeraddress = custInfo.address;
			customerarea = custInfo.area;
			this.sales_note = custInfo.note;
		}
		
		var billstatus:String = "PAID";
		var statusreason:String = "";
		
		Bill.Add(this.server,
			this.billCat,
			this.slotID,
			haveapptax,
			this.tax_amount,
			havediscount,
			this.discount_rate,
			this.discount_note,
			this.discount_amount,
			haveservcharg,
			this.service_charges,
			customernumber,
			customername,
			customeraddress,
			customerarea,
			salesnote,
			billstatus,
			statusreason,
			
			Number(this.txtTotal.text),
			this.lastQTNumber,
			this.arrBill
			);
		this.ShowReceipt(Bill.LastInsertRowID.toString(),this.arrBill,customername,customernumber,customeraddress,customerarea);	
		//Alert.show("Total Bill is " + this.txtTotal.text );
		this.arrBill = new Array();
		this.chkApplyTAX.selected = false;
		this.txtTotal.text = "0";
		this.txtCode.text = "";
		this.chkApplyTAX.label = "Apply TAX";
		this.txtBalance.text = "0";
		this.txtAmountPaid.text = "";
		this.dispatchEvent(new SlotStatusChangedEvent(SlotStatusChangedEvent.SLOT_STATUS_CHANGED,SlotStatus.FREE,null,true));
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function ShowReceipt(parmQTNumber:String,parmItems:Array,parmCustomerName:String,parmCustomerNumber:String,parmCustomerAddress:String,parmCustomerArea:String):void{
	try{
		var printBill:twClientBill = PopUpManager.createPopUp(this,twClientBill,true) as twClientBill;
		printBill.SetValues(parmQTNumber,this.billCat,this.slotID.toString(),this.server,parmItems,parmCustomerName,parmCustomerNumber,parmCustomerAddress,
		parmCustomerArea,this.init_total.toString(),this.tax_amount.toString(),
		this.service_charges.toString(),this.discount_amount.toString(),this.txtTotal.text,
		this.txtAmountPaid.text,this.txtBalance.text,this.sales_note);
		PopUpManager.centerPopUp(printBill);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function ShowCounterReceipt(parmItems:Array):void{
	try{
		var printBill:twCounterCopyBill = PopUpManager.createPopUp(this,twCounterCopyBill,true) as twCounterCopyBill;
		printBill.SetValues(this.billCat,this.slotID.toString(),this.server,parmItems,
		this.init_total.toString(),this.tax_amount.toString(),
		this.service_charges.toString(),this.discount_amount.toString(),this.txtTotal.text);
		PopUpManager.centerPopUp(printBill);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function ResetKitchen_OnReasonCommitted(evt:ResetCommitted):void{
	try{
		this.isResetQT = true;
		for each ( var singleItem:Object in this.arrBill ){
			singleItem.status = "";
		}
		this.dgCurrentPurchase.dataProvider = this.arrBill;

		ResetBill.Add(this.server,
					this.billCat,
					this.slotID,
					Number(this.txtTotal.text),
					evt.Reason,
					this.lastQTNumber,
					this.arrBill);
		
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function ResetKitchen():void{
	try{
		var _wind:twResetReason = PopUpManager.createPopUp(this,twResetReason,true) as twResetReason;
		_wind.addEventListener(ResetCommitted.RESET_COMMITTED,this.ResetKitchen_OnReasonCommitted);
		PopUpManager.centerPopUp(_wind);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function OnDropBill(dropReason:String):void{
	try{
		this.Reset_OnClick();
		
		if ( this.arrBill.length == 0 ){
			this.dispatchEvent(new SlotStatusChangedEvent(SlotStatusChangedEvent.SLOT_STATUS_CHANGED,SlotStatus.FREE,null,true));
			return;
		} 
		var prt:Object = this.parent;
		var custInfo:Object = prt.CustomerInfo();

		var haveapptax:Number = this.chkApplyTAX.selected ? 1 : 0;
		var haveservcharg:Number = this.chkServiceCharges.selected ? 1 : 0;
		var havediscount:Number = this.chkDiscount.selected? 1 : 0;
		
		var customername:String = "";
		var customernumber:String = "";
		var customeraddress:String = "";
		var customerarea:String = "";
		var salesnote:String = "";
		
		if ( custInfo != null ){
			if ( custInfo.telephone == "" ){
				Alert.show("Customer Number is not defined");
				return;
			}
			if ( custInfo.name == "" ){
				Alert.show("Customer Name is not defined");
				return;
			}
			if ( custInfo.area == "" ){
				Alert.show("Customer Area is not defined");
				return;
			}
			if ( custInfo.address == "" ){
				Alert.show("Customer Address is not defined");
				return;
			}
			customername = custInfo.name;
			customernumber = custInfo.telephone;
			customeraddress = custInfo.address;
			customerarea = custInfo.area;
			salesnote = custInfo.note;
		}

		var billstatus:String = "DROP";
		var statusreason:String = dropReason;
		
		Bill.Add(this.server,
			this.billCat,
			this.slotID,
			haveapptax,
			this.tax_amount,
			havediscount,
			this.discount_rate,
			this.discount_note,
			this.discount_amount,
			haveservcharg,
			this.service_charges,
			customernumber,
			customername,
			customeraddress,
			customerarea,
			salesnote,
			billstatus,
			statusreason,
			
			Number(this.txtTotal.text),
			this.lastQTNumber,
			this.arrBill
			);
	
		this.arrBill = new Array();
		this.chkApplyTAX.selected = false;
		this.txtTotal.text = "0";
		this.txtCode.text = "";
		this.chkApplyTAX.label = "Apply TAX";
		this.txtBalance.text = "0";
		this.txtAmountPaid.text = "";
		this.dispatchEvent(new SlotStatusChangedEvent(SlotStatusChangedEvent.SLOT_STATUS_CHANGED,SlotStatus.FREE,null,true));
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnAmountDeliveryChargesChanged():void{
	try{
		this.ComputeTotal();
		this.OnAmountPaidChanged();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnAmountPaidKeyUp(evt:KeyboardEvent):void{
	try{
		switch(evt.keyCode){
			case Keyboard.EQUAL:
				this.txtAmountPaid.text = this.txtTotal.text;
				this.OnAmountPaidChanged();
			break;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnAmountPaidChanged():void{
	try{
		var amount:Number = Number(this.txtAmountPaid.text);
		var bill:Number = Number(this.txtTotal.text);
		this.btnPayBill.enabled = amount >= bill;
		this.txtBalance.text = (amount - bill).toString();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnPrintBill():void{
	try{
		if ( this.arrBill.length == 0 ) return;
		this.ShowCounterReceipt(this.arrBill);	
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnItemsMouseWheel(evt:MouseEvent):void{
	try{
		evt.delta = evt.delta > 0 ? 1 : -1;
	}catch(err:Error){
		Logger.LogE(err);
	}
}